<template>

  <div class="log_bg">
    <div class="top">
      <div class="logo">
        <a href="#"><img src="/images/logo.png" /></a>
      </div>
    </div>
    <div class="regist">
      <div class="log_img">
        <img src="/images/l_img.png" width="611" height="425" />
      </div>
      <div class="reg_c">
        <form @submit.prevent="onSubmit">
          <table border="0" style="width:420px; font-size:14px; margin-top:20px;" cellspacing="0" cellpadding="0">
            <tbody>
              <tr height="50" valign="top">
                <td width="95">&nbsp;</td>
                <td>
                  <span class="fl" style="font-size:24px;">注册</span>
                  <span class="fr">已有商城账号，<a href="#" @click.prevent="toLogin" style="color:#ff4e00;">我要登录</a></span>
                </td>
              </tr>
              <tr height="50">
                <td align="right">
                  <span color="#ff4e00">*</span>&nbsp;用户名 &nbsp;
                </td>
                <td>
                  <input v-model="form.username" type="text" class="l_user"  />
                  <span v-if="errors.userName" class="error-text">{{ errors.userName }}</span>
                </td>
              </tr>
              <tr height="50">
                <td align="right">
                  <span color="#ff4e00">*</span>&nbsp;账号 &nbsp;
                </td>
                <td>
                  <input v-model="form.loginName" @blur="checkLoginName" type="text" class="l_user"
                    :class="{ 'error': errors.loginName }"  />
                  <span v-if="errors.loginName" class="error-text">{{ errors.loginName }}</span>
                </td>
              </tr>
              <tr height="50">
                <td align="right">
                  <span color="#ff4e00">*</span>&nbsp;密码 &nbsp;
                </td>
                <td>
                  <input v-model="form.password" @blur="validatePassword" type="password" class="l_pwd"
                    :class="{ 'error': errors.password }"  />
                  <span v-if="errors.password" class="error-text">{{ errors.password }}</span>
                </td>
              </tr>
              <tr height="50">
                <td align="right">
                  <span color="#ff4e00">*</span>&nbsp;确认密码 &nbsp;
                </td>
                <td>
                  <input v-model="form.confirmPassword" @blur="validateConfirmPassword" type="password" class="l_pwd"
                    :class="{ 'error': errors.confirmPassword }"  />
                  <span v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</span>
                </td>
              </tr>
              <tr height="50">
                <td align="right">
                  <span color="#ff4e00">*</span>&nbsp;身份证号 &nbsp;
                </td>
                <td>
                  <input v-model="form.IDCard" @blur="validateIDCard" type="text" class="l_pwd"
                    :class="{ 'error': errors.IDCard }"  />
                  <span v-if="errors.IDCard" class="error-text">{{ errors.IDCard }}</span>
                </td>
              </tr>
              <tr height="50">
                <td align="right">
                  <span color="#ff4e00">*</span>&nbsp;性别 &nbsp;
                </td>
                <td>
                  <label>
                    <input type="radio" v-model="form.gender" value="1"  />&nbsp;男&nbsp;&nbsp;
                  </label>
                  <label>
                    <input type="radio" v-model="form.gender" value="0"  />&nbsp;女&nbsp;&nbsp;
                  </label>
                  <span v-if="errors.gender" class="error-text">{{ errors.gender }}</span>
                </td>
              </tr>
              <tr height="50">
                <td align="right">
                  <span color="#ff4e00">*</span>&nbsp;邮箱 &nbsp;
                </td>
                <td>
                  <input v-model="form.email" @blur="validateEmail" type="text" class="l_email"
                    :class="{ 'error': errors.email }"  />
                  <span v-if="errors.email">{{ errors.email }}</span>
                </td>
              </tr>
              <tr height="50">
                <td align="right">
                  <span color="#ff4e00">*</span>&nbsp;手机 &nbsp;
                </td>
                <td>
                  <input v-model="form.phone" @blur="validatePhone" type="text" class="l_tel"
                    :class="{ 'error': errors.phone }"  />
                  <span v-if="errors.phone" class="error-text">{{ errors.phone }}</span>
                </td>
              </tr>

              <tr height="50">
                <td align="right">
                  <span color="#ff4e00">*</span>&nbsp;验证码 &nbsp;
                </td>
                <td>
                  <input v-model="form.captcha" @blur="validateCaptcha" type="text" class="l_ipt"
                    :class="{ 'error': errors.captcha }"  />
                  <a href="#" @click.prevent="getCaptcha" style="font-size:12px; font-family:'宋体';">
                    {{ captchaText }}
                  </a>
                  <span v-if="errors.captcha" class="error-text">{{ errors.captcha }}</span>
                </td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td style="font-size:12px; padding-top:20px;">
                  <span style="font-family:'宋体';" class="fl">
                    <label class="r_rad">
                      <input type="checkbox" v-model="form.agree"  />
                    </label>
                    <label class="r_txt">我已阅读并接受《用户协议》</label>
                  </span>
                </td>
              </tr>
              <tr height="60">
                <td>&nbsp;</td>
                <td><input type="submit" value="立即注册" class="log_btn" :disabled="isSubmitting" /></td>
              </tr>
            </tbody>
          </table>
        </form>
      </div>
    </div>
  </div>
  <!--End Login End-->
  <!--Begin Footer Begin-->
  <div class="btmbg">
    <div class="btm">
      备案/许可证编号：蜀ICP备12009302号-1-www.dingguagua.com Copyright © 2015-2018 尤洪商城网 All Rights Reserved. 复制必究 ,
      Technical Support: Dgg Group <br />
      <img src="/images/b_1.gif" width="98" height="33" />
      <img src="/images/b_2.gif" width="98" height="33" />
      <img src="/images/b_3.gif" width="98" height="33" />
      <img src="/images/b_4.gif" width="98" height="33" />
      <img src="/images/b_5.gif" width="98" height="33" />
      <img src="/images/b_6.gif" width="98" height="33" />
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCurrentInstance } from 'vue'
import store from '@/store'

const router = useRouter()
const { proxy } = getCurrentInstance()

const form = reactive({
  username: '',
  loginName: '',
  password: '',
  confirmPassword: '',
  IDCard: '',
  gender: '1',
  email: '',
  phone: '',
  captcha: '',
  agree: false
})

const errors = reactive({})
const isSubmitting = ref(false)
const loginNameChecking = ref(false)
const captchaText = ref('获取验证码')
const captchaTimer = ref(null)
const isCaptchaDisabled = ref(false)
const isCaptchaExpired = ref(false)

const toLogin = () => {
  router.push({ name: 'login' })
}

// 验证用户名
const validateUsername = () => {
  if (!form.username.trim()) {
    errors.username = '请输入用户名'
    return false
  } else if (form.username.length < 3) {
    errors.username = '用户名至少3个字符'
    return false
  } else {
    delete errors.username
    return true
  }
}

const validateLoginName = () => {
  if (!form.loginName.trim()) {
    errors.loginName = '请输入账号'
    return false
  } else if (form.loginName.length < 3) {
    errors.loginName = '账号至少3个字符'
    return false
  } else {
    delete errors.loginName
    return true
  }
}

// 检查账号是否已存在
const checkLoginName = async () => {
  if (!validateLoginName()) return

  loginNameChecking.value = true
  const response = await proxy.axios.get('/api/judgeLoginName', {
    params: { loginName: form.loginName }
  })


  if (response.data.code === 5500) {
    errors.loginName = '账号已存在'
  } else {
    delete errors.loginName
  }

  loginNameChecking.value = false
}

// 验证密码
const validatePassword = () => {
  if (!form.password) {
    errors.password = '请输入密码'
    return false
  } else if (form.password.length < 6) {
    errors.password = '密码至少6个字符'
    return false
  } else {
    delete errors.password
    return true
  }
}

// 验证确认密码
const validateConfirmPassword = () => {
  if (!form.confirmPassword) {
    errors.confirmPassword = '请再次输入密码'
    return false
  } else if (form.password !== form.confirmPassword) {
    errors.confirmPassword = '两次输入的密码不一致'
    return false
  } else {
    delete errors.confirmPassword
    return true
  }
}

const validateIDCard = () => {
  // 身份证号正则表达式（10位）
  const idCardRegex = /^[1-9][0-9]\d{8}$/

  if (!form.IDCard.trim()) {
    errors.IDCard = '请输入身份证号'
    return false
  } else if (!idCardRegex.test(form.IDCard)) {
    errors.IDCard = '身份证号格式不正确(10位数字，不能0开头)'
    return false
  } else {
    delete errors.IDCard
    return true
  }
}

// 验证邮箱
const validateEmail = async () => {
  if (!form.email) {
    errors.email = '请输入邮箱'
    return false
  } 

  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(form.email)) {
    errors.email = '邮箱格式应为（xxx@xxx.xxx）'
    return false
  }
  
  try {
    const response = await proxy.axios.get('/api/judgeEmail', {
      params: { email: form.email }
    })

    if (response.data.code === 5500) {
      errors.email = '邮箱已存在'
      return false
    } else {
      delete errors.email
      return true
    }
  } catch (error) {
    errors.email = '邮箱验证失败'
    return false
  }
}

// 验证手机号
const validatePhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!form.phone) {
    errors.phone = '请输入手机号'
    return false
  } else if (!phoneRegex.test(form.phone)) {
    errors.phone = '手机号格式不正确(13-19开头的11位数字)'
    return false
  } else {
    delete errors.phone
    return true
  }
}

// 获取验证码
const getCaptcha = async () => {
  // 如果验证码按钮被禁用，则不执行任何操作
  if (isCaptchaDisabled.value) {
    return
  }

  if (!validateEmail) {
    return
  }

  // 按钮禁用
  isCaptchaDisabled.value = true
  // 重置验证码过期状态
  isCaptchaExpired.value = false

  // 倒计时60秒
  let count = 60
  captchaText.value = '60秒后重新获取'

  captchaTimer.value = setInterval(() => {
    count--
    if (count > 0) {
      captchaText.value = `${count}秒后重新获取`
    } else {
      // 倒计时结束，重新启用按钮
      clearInterval(captchaTimer.value)
      captchaTimer.value = null
      captchaText.value = '获取验证码'
      isCaptchaDisabled.value = false
      
      isCaptchaExpired.value = true
    }
  }, 1000)

  // 发送获取验证码请求
  await proxy.axios.post('/api/sendEmail', form.email, {
    headers: {
      'Content-Type': 'text/plain'
    }
  })
  alert('验证码已发送至您的邮箱')

}

// 验证验证码
const validateCaptcha = async () => {
  if (!form.captcha.trim()) {
    errors.captcha = '请输入验证码'
    return false
  }
  
  // 先检查是否过期
  if (isCaptchaExpired.value) {
    errors.captcha = '验证码已过期，请重新获取'
    return false
  }
  
    const response = await proxy.axios.post('/api/getEmailCaptcha', form.email, {
      headers: {
        'Content-Type': 'text/plain'
      }
    })

    if (response.data.captcha === form.captcha) {
      delete errors.captcha
      return true
    } else {
      errors.captcha = '验证码不正确'
      return false
    }

}
// 表单验证
const validateForm = async () => {  // 改为异步函数
  const validations = [
    validateUsername(),
    validateLoginName(),
    validatePassword(),
    validateConfirmPassword(),
    validateIDCard(),
    validatePhone()
  ]
  
  // 等待所有同步验证完成
  const syncResults = validations.every(result => result === true)
  
  if (!syncResults) {
    return false
  }
  
  // 异步验证邮箱和验证码
  try {
    const [isEmailValid, isCaptchaValid] = await Promise.all([
      validateEmail(),
      validateCaptcha()
    ])
    
    return isEmailValid && isCaptchaValid
  } catch (error) {
    console.error('验证失败:', error)
    return false
  }
}

const onSubmit = async () => {
  if (!form.agree) {
    alert('请阅读并同意用户协议')
    return
  }

  // 改为等待异步验证
  const isValid = await validateForm()
  
  if (!isValid) {
    alert('请完善表单信息')
    return
  }

  isSubmitting.value = true

  try {
    const userData = {
      loginName: form.loginName,
      userName: form.username,
      password: form.password,
      email: form.email,
      sex: form.gender,
      mobile: form.phone,
      identityCode: form.IDCard,
    }

    const response = await proxy.axios.post('/api/addUser', userData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.data.code === 5200) {
      alert('注册成功')
      router.push({ name: 'login' })
    } else {
      alert('注册失败: ' + response.data.message)
    }
  } catch (error) {
    alert('注册失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

// 进入管理页面时隐藏HeaderView
onMounted(() => {
  store.commit('setShowPage', 1)
})

// 离开管理页面时恢复HeaderView
onUnmounted(() => {
  store.commit('setShowPage', 0)
})


</script>

<style>
.error {
  border: 1px solid #ff4e00;
}
</style>